package sessionbeans;

import java.util.List;

import javax.ejb.Stateless;
import org.jboss.ejb3.annotation.RemoteBinding;

import entities.*;
import javax.persistence.*;
/**
 * Session Bean implementation class PersonalBean
 */
@Stateless
@RemoteBinding(jndiBinding="ProfileBeanRemote")
public class ProfileBean implements ProfileBeanRemote {

	public static final String BAD_ABILITY_NAME = "Bad ability name, request not sent";
	public static final String ALREADY_PRESENT_ABILITY = "This ability is already present in the system";
	public static final String ALREADY_SENT_REQUEST = "You have already sent this request";
	public static final String REQUEST_SENT_CORRECTLY = "Request sent correctly";
	@PersistenceContext
	private EntityManager manager;
    /**
     * Default constructor. 
     */
    public ProfileBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public RegisteredUser getUser(String userId) {
		return manager.find(RegisteredUser.class, userId);
	}

	@Override
	public List<Declares> getAbilities(String userId) {
		Query query = manager.createQuery("select d from Declares as d where d.key.user = :userId");
		RegisteredUser user = manager.find(RegisteredUser.class, userId);
		query.setParameter("userId", user);
		return (List<Declares>)(query.getResultList());
	}

	@Override
	public String sendAbilityRequest(String userId, String abilityName) {
		if(!abilityName.matches(AdminBean.validAbilityName)){
			return BAD_ABILITY_NAME;
		}
		if(manager.find(Ability.class, abilityName) != null){
			return ALREADY_PRESENT_ABILITY;
		}
		RegisteredUser user = manager.find(RegisteredUser.class, userId);
		AskForAddingPK key = new AskForAddingPK(user, abilityName);
		AskForAdding request = manager.find(AskForAdding.class, key);
		if(request != null){
			return ALREADY_SENT_REQUEST;
		}
		request = new AskForAdding(user, abilityName);
		manager.persist(request);
		return REQUEST_SENT_CORRECTLY;
	}

}
